/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.class_finder;


import java.io.File;

public class ClassFinder {
	private final FileSystem fileSystem;

	public ClassFinder(FileSystem fileSystem) {
		this.fileSystem = fileSystem;
	}

	public <F extends FindAction> F findClasses(Class startingClass, F findAction) {
		findClasses(fileSystem.directoryContaining(startingClass), fileSystem.sourceRoot(startingClass),
			new AlwaysPassDirectoryCondition(), findAction);
		
		return findAction;
	}

	public void findClasses(File startFrom, File sourceRoot, DirectoryCondition directoryCondition,
		FindAction findAction) {

		findClasses(fileSystem.filesIn(startFrom), sourceRoot, directoryCondition, findAction);
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	private void findClasses(File[] files, File sourceRoot, DirectoryCondition directoryCondition,
		FindAction findAction) {

		for (File currentFile : files) {
			if (fileSystem.isClass(currentFile)) {
				findAction.perform(fileSystem.className(currentFile, sourceRoot));
			}
		}

		for (File currentFile : files) {
			if (directoryCondition.matches(currentFile)) {
				findClasses(fileSystem.filesIn(currentFile), sourceRoot, directoryCondition, findAction);
			}
		}
	}
}
